package com.aconcagua.mvc.factory {
  import com.aconcagua.beans.BeanDefinitionFactory;
  import com.aconcagua.beans.BeanDefinitionSupport;
  import com.aconcagua.beans.BeanList;
  import com.aconcagua.beans.ConstructorArg;
  import com.aconcagua.beans.Property;
  import com.aconcagua.factory.BeanFactory;
  import com.aconcagua.mvc.control.Controller;
  
  import mx.core.IMXMLObject;
  
  public class Controller implements BeanDefinitionFactory, IMXMLObject {
    private var _bean: BeanDefinitionSupport;
    
    private var _eventDispatcher: Object;
    private var _commandFactory: Object;
    private var _mappings: Array;
    private var _id: String;
    private var _type: Class;
    private var _commandExecutor: Object;

    public function Controller() {
      _type = com.aconcagua.mvc.control.Controller;
    }

    public function set type(aClass: Class): void {
      _type = aClass;
    }

    public function set commandExecutor(executor: Object): void {
      _commandExecutor = executor;
    }

    public function initialized(document:Object, id:String): void {
      _id = id;
    }

    public function  registerIn(beanFactory: BeanFactory): void {
      _bean = new BeanDefinitionSupport(_type, _id);
      _bean.scope = BeanDefinitionSupport.SCOPE_SINGLETON;
      _bean.addConstructorArg(new ConstructorArg(_eventDispatcher));
      _bean.addConstructorArg(new ConstructorArg(_commandFactory));
      _bean.addProperty(new Property("mappings", new BeanList(_mappings)));
      if (_commandExecutor != null) {
        _bean.addProperty(new Property("commandExecutor", _commandExecutor));
      }

      beanFactory.registerBeanDefinition(_bean);
    }

    public function isRegisteredIn(beanFactory: BeanFactory): Boolean {
      return beanFactory.containsBean(_bean.name);
    }
    
    public function retrieveFrom(beanFactory: BeanFactory): Object {
      return beanFactory.getBean(_bean.name);
    }

    public function set eventDispatcher(dispatcher: Object): void {
      _eventDispatcher = dispatcher;
    }
    
    public function set commandFactory(factory: Object): void {
      _commandFactory = factory;
    }
    
    /**
    * @param array array of FactoryBean that creates 
    *              com.aconcagua.mvc.control.GestureMapping objects
    **/
    public function set mappings(array: Array): void {
      _mappings = array;
    }
  }
}